package com.haohan.jingyuan.customer.service;

import com.haohan.jingyuan.common.enums.ErrorEnum;
import com.haohan.jingyuan.common.exception.BusinessException;
import com.haohan.jingyuan.common.util.EntityUtil;
import com.haohan.jingyuan.customer.dao.CustomerGroupMapper;
import com.haohan.jingyuan.customer.dao.CustomerInfoMapper;
import com.haohan.jingyuan.customer.dto.req.CreateGroupRequest;
import com.haohan.jingyuan.customer.dto.req.DeleteGroupRequest;
import com.haohan.jingyuan.customer.dto.req.QueryGroupListRequest;
import com.haohan.jingyuan.customer.dto.req.UpdateGroupRequest;
import com.haohan.jingyuan.customer.dto.resp.GroupInfoResp;
import com.haohan.jingyuan.customer.dto.resp.GroupListResp;
import com.haohan.jingyuan.customer.entity.CustomerGroupInfo;
import com.haohan.jingyuan.customer.helper.GroupRespHelper;
import com.haohan.jingyuan.gateway.holder.UserContextHolder;
import com.haohan.jingyuan.util.UuidUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户分组服务实现类
 *
 * @ClassName CustomerGroupService
 * @Description 客户分组相关业务逻辑实现
 * @Author hexijun
 * @Time 2025/01/19 20:00
 * @Version 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomerGroupService {

    /**
     * 客户分组Mapper
     */
    private final CustomerGroupMapper customerGroupMapper;

    /**
     * 客户信息Mapper
     */
    private final CustomerInfoMapper customerInfoMapper;

    /**
     * 创建分组
     *
     * @param request 创建分组请求
     * @return 分组信息
     */
    public GroupInfoResp createGroup(CreateGroupRequest request) {
        // 检查分组名称是否已存在
        CustomerGroupInfo existingGroup = customerGroupMapper.findByGroupName(request.getGroupName());
        if (existingGroup != null) {
            throw new BusinessException(ErrorEnum.GROUP_ALREADY_EXISTS);
        }

        // 校验上级分组是否存在
        if (request.getParentGroupId() != null && !request.getParentGroupId().trim().isEmpty()) {
            CustomerGroupInfo parentGroup = customerGroupMapper.findByGroupId(request.getParentGroupId());
            if (parentGroup == null) {
                throw new BusinessException(ErrorEnum.GROUP_NOT_FOUND);
            }
        }

        // 生成分组ID
        String groupId = UuidUtil.generateId("GROUP", 10);

        // 创建分组记录
        CustomerGroupInfo customerGroupInfo = new CustomerGroupInfo();
        customerGroupInfo.setGroupId(groupId);
        customerGroupInfo.setGroupName(request.getGroupName());
        customerGroupInfo.setType(request.getType());
        customerGroupInfo.setParentGroupId(request.getParentGroupId());
        customerGroupInfo.setDescription(request.getDescription());
        // ukid默认为0
        customerGroupInfo.setUkid(0L);
        EntityUtil.setCreateAndModifyInfo(customerGroupInfo, UserContextHolder.getCurrentUserName());

        // 保存到数据库
        int result = customerGroupMapper.insert(customerGroupInfo);
        if (result <= 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }
        return GroupRespHelper.convert2GroupInfoResp(customerGroupInfo);
    }

    /**
     * 更新分组
     *
     * @param request 更新分组请求
     * @return 分组信息
     */
    public GroupInfoResp updateGroup(UpdateGroupRequest request) {
        // 查询分组是否存在
        Long id = Long.parseLong(request.getId());
        CustomerGroupInfo customerGroupInfo = customerGroupMapper.selectById(id);
        if (customerGroupInfo == null) {
            throw new BusinessException(ErrorEnum.GROUP_NOT_FOUND);
        }

        // 校验上级分组是否存在
        if (request.getParentGroupId() != null && !request.getParentGroupId().trim().isEmpty()) {
            CustomerGroupInfo parentGroup = customerGroupMapper.findByGroupId(request.getParentGroupId());
            if (parentGroup == null) {
                throw new BusinessException(ErrorEnum.GROUP_NOT_FOUND);
            }
            if(!customerGroupInfo.getType().equals(parentGroup.getType())){
                throw new BusinessException(ErrorEnum.GROUP_TYPE_MUST_SAME);
            }
            // 防止设置自己为自己的上级分组
            if (customerGroupInfo.getGroupId().equals(request.getParentGroupId())) {
                throw new BusinessException(ErrorEnum.GROUP_CANNOT_BE_PARENT_OF_ITSELF);
            }
        }

        // 更新分组信息
        if (request.getGroupName() != null) {
            customerGroupInfo.setGroupName(request.getGroupName());
        }
        if (request.getParentGroupId() != null) {
            customerGroupInfo.setParentGroupId(request.getParentGroupId());
        }
        if (request.getDescription() != null) {
            customerGroupInfo.setDescription(request.getDescription());
        }
        EntityUtil.setModifyInfo(customerGroupInfo, UserContextHolder.getCurrentUserName());

        // 更新数据库
        int result = customerGroupMapper.updateById(customerGroupInfo);
        if (result <= 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }
        return GroupRespHelper.convert2GroupInfoResp(customerGroupInfo);
    }

    /**
     * 删除分组
     *
     * @param request 删除分组请求
     * @return 删除结果
     */
    public boolean deleteGroup(DeleteGroupRequest request) {
        // 查询分组是否存在
        Long id = Long.parseLong(request.getId());
        CustomerGroupInfo customerGroupInfo = customerGroupMapper.selectById(id);
        if (customerGroupInfo == null) {
            throw new BusinessException(ErrorEnum.GROUP_NOT_FOUND);
        }

        // 校验是否有子分组
        int childGroupCount = customerGroupMapper.countByParentGroupId(customerGroupInfo.getGroupId());
        if (childGroupCount > 0) {
            throw new BusinessException(ErrorEnum.GROUP_HAS_CHILDREN);
        }

        // 校验是否有客户正在使用该分组
        int usingCount = customerInfoMapper.countByCategory(customerGroupInfo.getGroupId());
        if (usingCount > 0) {
            throw new BusinessException(ErrorEnum.GROUP_IN_USE);
        }

        // 设置ukid为记录主键id
        customerGroupInfo.setUkid(id);
        EntityUtil.setModifyInfo(customerGroupInfo, UserContextHolder.getCurrentUserName());

        // 更新数据库
        int result = customerGroupMapper.updateById(customerGroupInfo);
        if (result <= 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }
        return true;
    }

    /**
     * 查询分组列表
     *
     * @param request 查询分组列表请求
     * @return 分组列表（树状结构）
     */
    public GroupListResp queryGroupList(QueryGroupListRequest request) {
        // 查询所有符合type的分组
        List<CustomerGroupInfo> groupList = customerGroupMapper.selectByType(request.getType());

        // 转换为响应对象并建立映射关系
        Map<String, GroupInfoResp> groupMap = new HashMap<>();
        List<GroupInfoResp> topLevelGroups = new ArrayList<>();

        // 第一遍遍历：转换所有分组并建立映射
        for (CustomerGroupInfo record : groupList) {
            GroupInfoResp groupInfoResp = GroupRespHelper.convert2GroupInfoResp(record);
            groupInfoResp.setChildren(new ArrayList<>());
            groupMap.put(groupInfoResp.getGroupId(), groupInfoResp);
        }

        // 第二遍遍历：构建树状结构
        for (GroupInfoResp groupInfoResp : groupMap.values()) {
            String parentGroupId = groupInfoResp.getParentGroupId();
            if (parentGroupId == null || parentGroupId.trim().isEmpty()) {
                // 顶级分组
                topLevelGroups.add(groupInfoResp);
            } else {
                // 子分组，添加到父分组的children列表中
                GroupInfoResp parentGroup = groupMap.get(parentGroupId);
                if (parentGroup != null) {
                    parentGroup.getChildren().add(groupInfoResp);
                } else {
                    // 如果父分组不存在，也作为顶级分组处理（防止数据异常）
                    topLevelGroups.add(groupInfoResp);
                }
            }
        }

        GroupListResp response = new GroupListResp();
        response.setGroupList(topLevelGroups);
        return response;
    }
}
